#include "music.h"
#include "ui_music.h"

Music::Music(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Music)
{
    ui->setupUi(this);

    pModel = new QStandardItemModel(10,5,ui->tableView);

    QStringList list = QStringList()<<"歌名"<<"歌手"<<"专辑"<<"时长"<<"喜欢";




    pModel->setHorizontalHeaderLabels(list);//设置数据的表头

    ui->tableView->setModel(pModel);

    ui->tableView->setStyleSheet(
        "QTableView { " "    background: transparent; "
        "    gridline-color: transparent; "
        "}"
        "QHeaderView { "
        "    background: transparent; "
        "    border: none; "
        "}"
    );
   ui->tableView->setSelectionMode(QAbstractItemView::NoSelection);




//    ui->tableView->setStyleSheet("background-image: url(':/D:/photo/1.webp');"
//                                     "background-repeat: no-repeat;"       // 不重复
//                                     "background-position: center;"         // 居中显示
//                                     "background-attachment: fixed;"        // 固定背景
//                                     "background-size: cover;");





    // 设置背景图片
    // 设置背景图片
//      ui->tableView->setStyleSheet("QTableView {"
//                                "background-image: url(':/D:/photo/3.jpeg');"
//                                "background-repeat: no-repeat;"       // 不重复
//                                "background-position: center;"         // 居中显示
//                                "background-attachment: fixed;"        // 固定背景
//                                "}");
      ui->pushButton_2->setStyleSheet("QPushButton{" "background-image: url(':/D:/photo/1.png');"
                                       "background-position: center;"
                                          "background-color: rgba(0, 0, 0, 0);"
                                      "}");
      ui->pushButton_3->setStyleSheet("QPushButton{" "background-image: url(':/D:/photo/5.png');"
                                       "background-position: center;"
                                          "background-color: rgba(0, 0, 0, 0);"
                                      "}");
      ui->pushButton_4->setStyleSheet("QPushButton{" "background-image: url(':/D:/photo/4.png');"
                                       "background-position: center;"
                                          "background-color: rgba(0, 0, 0, 0);"

                                      "}");



      //表列随着表格变化而自适应变化
      ui->tableView->horizontalHeader()-> setSectionResizeMode(QHeaderView::Stretch);
      //表行随着表格变化而自适应变化
       ui->tableView->verticalHeader()-> setSectionResizeMode(QHeaderView::Stretch);






         ui->tableView->show();







    manager = new QNetworkAccessManager(this);
    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));

    ui->tableView->horizontalHeader()->setStyleSheet("QHeaderView::section{background-color: transparent;};selection-background-color: rgb(77, 77, 77);");

    playlist = new QMediaPlaylist;//媒体播放列表
    player = new QMediaPlayer;//媒体播放器


    player->setPlaylist(playlist);
    connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(positionChangedSlot(qint64)));
    connect(player,SIGNAL(durationChanged(qint64)),this,SLOT(durationChangedSlot(qint64)));



}


Music::~Music()
{
    delete ui;
}

void Music::replyFinished(QNetworkReply* reply)
{
      if(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute)==200)
      {
          qDebug()<<"服务器访问成功"<<endl;

         parseJson(reply->readAll());
      }
}


void Music::parseJson(QByteArray byteArray)
{
   unsigned int id = 0;
   QString songName;
   QString albumName;
   QString singerName;
   QString songtime;
    QString duration;
//   float duration = -1;
   musicIDList.clear();
   playlist->clear();

    QJsonDocument doc = QJsonDocument::fromJson(byteArray);//直接从字节数组中获得一个JSON文档
    if(doc.isObject())//询问文档内部是否是一个对象
    {
            qDebug()<<"该文档是一个对象"<<endl;
            QJsonObject obj1 = doc.object();//返回文档的对象
            if(obj1.contains("result")==false)//询问文档对象是否含result关键字
            {
                qDebug()<<"错误的JSON对象"<<endl;
                return;
            }
            QJsonValue var = obj1.value("result");//获得关键字result对应的结果
            if(var.isObject()==false)
            {
                qDebug()<<"result的值不是对象"<<endl;
                return;
            }
            QJsonObject resultObj = var.toObject();//把result的值转为对象
            if(resultObj .contains("songs")==false)
            {
                qDebug()<<"JSON对象没有歌曲"<<endl;
                return;
            }
             var = resultObj.value("songs");//得到关键字songs的值
            if(var.isArray())//询问是否为数组
            {
                songsArry = var.toArray();//将songs的值转为一个数组
                qDebug()<<"一共搜索到"<<songsArry.size()<<"首歌曲"<<endl;
                for(int i = 0;i<songsArry.size();i++)
                {
                    QJsonObject songsObj = songsArry[i].toObject();
                    if(songsObj.contains("id"))
                    {
                        QJsonValue varID = songsObj.value("id");//获取关键字为id的元素的值
                        id = varID.toDouble();//为了避免数组越界，使用double类型返回ID号
                    }
                    if(songsObj.contains("name"))
                    {
                        QJsonValue varName = songsObj.value("name");//获取关键字为name的元素的值
                        songName = varName.toString();
                    }

                    if(songsObj.contains("album"))//是否包含专辑
                                   {
                                       QJsonValue varAlbum = songsObj.value("album");//得到专辑关键字的值
                                       if(varAlbum.isObject())
                                       {
                                           QJsonObject albumObj = varAlbum.toObject();//把专辑的值转为对象
                                           if(albumObj.contains("name"))
                                           {
                                               QJsonValue varAlbumName =  albumObj.value("name");
                                               albumName = varAlbumName.toString();//得到专辑名
                                           }
                                       }
                                   }
                    if(songsObj.contains("artists"))//是否包含作者关键字
                                   {
                                       QJsonValue varArtists = songsObj.value("artists");
                                       if(varArtists.isArray())//作者的值是否为数组？
                                       {
                                          QJsonArray arrArtists = varArtists.toArray();
                                          for (int i = 0; i < arrArtists.size(); ++i) {//遍历作者数组
                                              if(arrArtists[i].isObject())
                                              {
                                                  QJsonObject artistsObj = arrArtists[i].toObject();
                                                  if(artistsObj.contains("name"))
                                                  {
                                                      QJsonValue varArtistsName = artistsObj.value("name");
                                                      singerName+= varArtistsName.toString();//把名字加入到字符串中
                                                      singerName+=" ";//中间留一个空格
                                                  }
                                              }
                                          }
                                       }
                                   }
                                   if(songsObj.contains("duration"))
                                                  {

                                                      QJsonValue varDuration = songsObj.value("duration");//获取关键字为duration的元素的值
                                                      int var_time = varDuration.toInt();
                                                      int min=var_time/1000/60;
                                                      int sec=var_time/100%60;
                                                      duration=QString("%0分:%1秒").arg(min).arg(sec);
                                                  }
                                                  qDebug()<<id<<" "<<songName<<" "<<albumName<<" "<<singerName<<" "<<duration<<endl;

                     musicIDList.push_back(id);

playlist->addMedia(QUrl(QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(id)));
                //把解析出来的歌曲信息加入到QTableView的数据模型中
               QStandardItem *item = new QStandardItem(songName);//歌名
               pModel->setItem(i, 0, item);
               item->setForeground(QBrush(QColor(Qt::green)));

               item = new QStandardItem(albumName);
               pModel->setItem(i, 1, item);
               item->setForeground(QBrush(QColor(Qt::green)));

               item = new QStandardItem(singerName);
               pModel->setItem(i, 2, item);
               item->setForeground(QBrush(QColor(Qt::green)));

               item = new QStandardItem(QString("%0").arg(duration));
               pModel->setItem(i, 3, item);
               item->setForeground(QBrush(QColor(Qt::green)));

////                在指定单元格插入图片
                   itemWithImage = new QStandardItem();
                   QPixmap pixmap(":/D:/photo/6.png"); // 更改为你图片的路径
                   itemWithImage->setData(QPixmap(pixmap), Qt::DecorationRole); // 将图片设置为装饰角色

                   pModel->setItem(i, 4, itemWithImage); // 在 (0, 0) 插入图片


               singerName = "";//清空歌手名
                }
                 ui->tableView->setModel(pModel);
                playlist->setCurrentIndex(0);
            }
    }

}

void Music::parseJson_2(QByteArray byteArray)
{
    QString lyricName;

    QJsonDocument doc = QJsonDocument::fromJson(byteArray);//直接从字节数组中获得一个JSON文档
    if(doc.isObject())//询问文档内部是否是一个对象
    {
        qDebug()<<"该文档是一个对象"<<endl;
        QJsonObject obj1 = doc.object();//返回文档的对象
        if(obj1.contains("lrc")==false)//询问文档对象是否含lrc关键字
        {
            qDebug()<<"错误的JSON对象"<<endl;
            return;
        }
        QJsonValue var = obj1.value("lrc");//获得关键字lrc对应的结果
        if(var.isObject()==false)
        {
            qDebug()<<"lrc的值不是对象"<<endl;
            return;
        }
        QJsonObject lrcObj = var.toObject();//把lrc的值转为对象

        if(lrcObj.contains("lyric"))
        {
            QJsonValue lyric = lrcObj.value("lyric");//获取关键字为lyric的元素的值
            lyricName = lyric.toString();
        }
        qDebug()<<lyricName<<endl;
    }


}

void Music::on_pushButton_clicked()
{
 manager->get(QNetworkRequest(QUrl(QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=1&offset=0&total=true&limit=10").arg(ui->lineEdit->text()))));
}

void Music::on_tableView_doubleClicked(const QModelIndex &index)
{

    qDebug()<<index<<endl;

     playlist->setCurrentIndex(index.row());
     ui->pushButton_2->setStyleSheet("QPushButton{" "background-image: url(':/D:/photo/2.png');"
                                      "background-position: center;"
                                         "background-color: rgba(0, 0, 0, 0);"
                                     "}");
     player->play();



}

void Music::positionChangedSlot(qint64 position)
{
    qDebug()<<position<<endl;
    ui->horizontalSlider->setValue(position);
}


 void Music::durationChangedSlot(qint64 duration)
 {
     qDebug()<<"当前歌曲的总时长为"<<duration<<"毫秒"<<endl;
     ui->horizontalSlider->setRange(0,duration);//设置滑块的总范围为歌曲的时长
 }

 void Music::on_horizontalSlider_sliderReleased()
 {
     qint64 var = ui->horizontalSlider->value();//得到滑块当前值
     player->setPosition(var);//得到滑块当前值做为音乐播放的当前时间
 }


void Music::on_pushButton_2_clicked()
{

    if(player->state()==player->PlayingState)
    {
        ui->pushButton_2->setStyleSheet("QPushButton{" "background-image: url(':/D:/photo/1.png');"
                                         "background-position: center;"
                                            "background-color: rgba(0, 0, 0, 0);"
                                        "}");
        player->pause();
    }
    else
    {
        ui->pushButton_2->setStyleSheet("QPushButton{" "background-image: url(':/D:/photo/2.png');"
                                         "background-position: center;"
                                            "background-color: rgba(0, 0, 0, 0);"

                                        "}");
        player->play();
    }

}

void Music::on_pushButton_3_clicked()
{

    int count = playlist->mediaCount(); // 判断音乐的个数
        if(count == 0)
        {
            return;
        }

        /* 跳转到列表的上一个 */
        playlist->previous();
        ui->pushButton_2->setStyleSheet("QPushButton{" "background-image: url(':/D:/photo/2.png');"
                                         "background-position: center;"
                                            "background-color: rgba(0, 0, 0, 0);"
                                        "}");
        player->play(); // 播放音乐

}

void Music::on_pushButton_4_clicked()
{
    int count = playlist->mediaCount(); // 判断音乐的个数
        if(count == 0)
        {
            return;
        }

        /* 跳转到列表的下一个 */
        playlist->next();
        ui->pushButton_2->setStyleSheet("QPushButton{" "background-image: url(':/D:/photo/2.png');"
                                         "background-position: center;"
                                            "background-color: rgba(0, 0, 0, 0);"
                                        "}");
        player->play(); // 播放音乐
}
